import { useState } from 'react';
import AdminLayout from '../../components/admin/AdminLayout';
import DataTable from '../../components/admin/tables/DataTable';
import LineChart from '../../components/admin/charts/LineChart';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faSearch, faFilter, faDownload, faChartLine,
  faHeartbeat, faWeight, faWalking, faBed, faTint, faFire
} from '@fortawesome/free-solid-svg-icons';

export default function HealthDataManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('all');
  const [selectedUser, setSelectedUser] = useState(null);
  
  // 模拟健康数据
  const healthData = [
    { 
      id: 1, 
      userId: 1, 
      username: '健康达人123', 
      type: 'weight', 
      typeName: '体重',
      value: 72.5, 
      unit: 'kg', 
      recordedAt: '2023-11-05 08:30', 
      typeIcon: faWeight
    },
    { 
      id: 2, 
      userId: 1, 
      username: '健康达人123', 
      type: 'steps', 
      typeName: '步数',
      value: 8500, 
      unit: '步', 
      recordedAt: '2023-11-05 22:00', 
      typeIcon: faWalking
    },
    { 
      id: 3, 
      userId: 2, 
      username: '跑步爱好者', 
      type: 'heart_rate', 
      typeName: '心率',
      value: 72, 
      unit: 'bpm', 
      recordedAt: '2023-11-05 19:15', 
      typeIcon: faHeartbeat
    },
    { 
      id: 4, 
      userId: 2, 
      username: '跑步爱好者', 
      type: 'steps', 
      typeName: '步数',
      value: 12500, 
      unit: '步', 
      recordedAt: '2023-11-05 21:30', 
      typeIcon: faWalking
    },
    { 
      id: 5, 
      userId: 3, 
      username: '营养师小王', 
      type: 'water', 
      typeName: '饮水量',
      value: 2200, 
      unit: 'ml', 
      recordedAt: '2023-11-05 20:00', 
      typeIcon: faTint
    },
    { 
      id: 6, 
      userId: 3, 
      username: '营养师小王', 
      type: 'calories', 
      typeName: '热量',
      value: 1850, 
      unit: 'kcal', 
      recordedAt: '2023-11-05 21:00', 
      typeIcon: faFire
    },
    { 
      id: 7, 
      userId: 4, 
      username: '睡眠研究者', 
      type: 'sleep', 
      typeName: '睡眠',
      value: 7.5, 
      unit: 'h', 
      recordedAt: '2023-11-05 09:00', 
      typeIcon: faBed
    },
    { 
      id: 8, 
      userId: 5, 
      username: '健身教练', 
      type: 'weight', 
      typeName: '体重',
      value: 68.2, 
      unit: 'kg', 
      recordedAt: '2023-11-05 07:30', 
      typeIcon: faWeight
    },
    { 
      id: 9, 
      userId: 5, 
      username: '健身教练', 
      type: 'calories', 
      typeName: '热量',
      value: 2200, 
      unit: 'kcal', 
      recordedAt: '2023-11-05 22:15', 
      typeIcon: faFire
    },
    { 
      id: 10, 
      userId: 6, 
      username: '瑜伽爱好者', 
      type: 'heart_rate', 
      typeName: '心率',
      value: 65, 
      unit: 'bpm', 
      recordedAt: '2023-11-05 18:45', 
      typeIcon: faHeartbeat
    }
  ];

  // 模拟趋势数据
  const trendData = {
    weight: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [73.1, 72.9, 72.8, 72.6, 72.8, 72.7, 72.5],
      title: '体重趋势 (kg)'
    },
    steps: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [7500, 8200, 7800, 8500, 9100, 8300, 8500],
      title: '步数趋势 (步)'
    },
    heart_rate: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [68, 70, 72, 71, 69, 70, 72],
      title: '心率趋势 (bpm)'
    },
    sleep: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [7.2, 6.8, 7.5, 8.0, 7.1, 7.3, 7.5],
      title: '睡眠趋势 (小时)'
    },
    water: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [1800, 2000, 2100, 1900, 2200, 2150, 2200],
      title: '饮水量趋势 (ml)'
    },
    calories: {
      labels: ['10-30', '10-31', '11-01', '11-02', '11-03', '11-04', '11-05'],
      data: [1920, 1850, 1900, 1950, 1880, 1920, 1850],
      title: '热量趋势 (kcal)'
    }
  };

  // 用户列表
  const users = [...new Set(healthData.map(item => item.username))].map(username => {
    const user = healthData.find(item => item.username === username);
    return { id: user.userId, name: username };
  });

  // 数据类型列表
  const dataTypes = [
    { value: 'all', label: '全部类型', icon: faChartLine },
    { value: 'weight', label: '体重', icon: faWeight },
    { value: 'steps', label: '步数', icon: faWalking },
    { value: 'heart_rate', label: '心率', icon: faHeartbeat },
    { value: 'sleep', label: '睡眠', icon: faBed },
    { value: 'water', label: '饮水量', icon: faTint },
    { value: 'calories', label: '热量', icon: faFire },
  ];

  // 过滤数据
  const filteredData = healthData.filter(item => {
    const matchesSearch = 
      item.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.value.toString().includes(searchTerm);
    
    const matchesType = selectedType === 'all' || item.type === selectedType;
    const matchesUser = !selectedUser || item.userId === selectedUser;
    
    return matchesSearch && matchesType && matchesUser;
  });

  // 表格列配置
  const columns = [
    { 
      key: 'type', 
      title: '数据类型', 
      sortable: true,
      render: (item) => (
        <div className="flex items-center">
          <div className={`p-2 rounded-full mr-3 ${
            item.type === 'weight' ? 'bg-blue-100 text-blue-600' :
            item.type === 'steps' ? 'bg-green-100 text-green-600' :
            item.type === 'heart_rate' ? 'bg-red-100 text-red-600' :
            item.type === 'sleep' ? 'bg-purple-100 text-purple-600' :
            item.type === 'water' ? 'bg-indigo-100 text-indigo-600' :
            'bg-amber-100 text-amber-600'
          }`}>
            <FontAwesomeIcon icon={item.typeIcon} />
          </div>
          <span className="text-sm font-medium text-gray-900">{item.typeName}</span>
        </div>
      )
    },
    { 
      key: 'value', 
      title: '数值', 
      sortable: true,
      render: (item) => (
        <div className="text-sm font-medium text-gray-900">
          {item.value} <span className="text-gray-500 text-xs">{item.unit}</span>
        </div>
      )
    },
    { 
      key: 'username', 
      title: '用户', 
      sortable: true 
    },
    { 
      key: 'recordedAt', 
      title: '记录时间', 
      sortable: true 
    },
  ];

  // 处理操作
  const handleView = (data) => {
    console.log('查看数据:', data);
    setSelectedUser(data.userId);
    setSelectedType(data.type);
  };

  const handleEdit = (data) => {
    console.log('编辑数据:', data);
    // 实现编辑数据的逻辑
  };

  const handleDelete = (data) => {
    console.log('删除数据:', data);
    // 实现删除数据的逻辑
  };

  // 获取当前选择类型的趋势数据
  const currentTrendData = trendData[selectedType !== 'all' ? selectedType : 'weight'];

  return (
    <AdminLayout>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">健康数据管理</h1>
        <p className="mt-1 text-sm text-gray-600">查看和管理用户的健康数据记录。</p>
      </div>

      {/* 趋势图 */}
      {currentTrendData && (
        <div className="mb-8">
          <LineChart 
            title={currentTrendData.title}
            labels={currentTrendData.labels}
            data={currentTrendData.data}
            borderColor={
              selectedType === 'weight' ? 'rgba(59, 130, 246, 1)' :
              selectedType === 'steps' ? 'rgba(16, 185, 129, 1)' :
              selectedType === 'heart_rate' ? 'rgba(239, 68, 68, 1)' :
              selectedType === 'sleep' ? 'rgba(139, 92, 246, 1)' :
              selectedType === 'water' ? 'rgba(99, 102, 241, 1)' :
              selectedType === 'calories' ? 'rgba(245, 158, 11, 1)' :
              'rgba(59, 130, 246, 1)'
            }
            backgroundColor={
              selectedType === 'weight' ? 'rgba(59, 130, 246, 0.1)' :
              selectedType === 'steps' ? 'rgba(16, 185, 129, 0.1)' :
              selectedType === 'heart_rate' ? 'rgba(239, 68, 68, 0.1)' :
              selectedType === 'sleep' ? 'rgba(139, 92, 246, 0.1)' :
              selectedType === 'water' ? 'rgba(99, 102, 241, 0.1)' :
              selectedType === 'calories' ? 'rgba(245, 158, 11, 0.1)' :
              'rgba(59, 130, 246, 0.1)'
            }
          />
        </div>
      )}

      {/* 过滤选项 */}
      <div className="mb-6 flex flex-col space-y-4 lg:space-y-0 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-col md:flex-row items-start md:items-center gap-4">
          {/* 搜索框 */}
          <div className="w-full md:w-64 relative">
            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
              <FontAwesomeIcon icon={faSearch} className="text-gray-400" />
            </div>
            <input
              type="text"
              placeholder="搜索数据..."
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* 用户选择 */}
          <div className="w-full md:w-48">
            <select
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              value={selectedUser || ''}
              onChange={(e) => setSelectedUser(e.target.value ? Number(e.target.value) : null)}
            >
              <option value="">所有用户</option>
              {users.map((user) => (
                <option key={user.id} value={user.id}>{user.name}</option>
              ))}
            </select>
          </div>
        </div>

        {/* 数据类型过滤 */}
        <div className="flex flex-wrap gap-2">
          {dataTypes.map((type) => (
            <button
              key={type.value}
              className={`flex items-center px-3 py-1.5 text-sm font-medium rounded-md ${
                selectedType === type.value
                  ? 'bg-blue-100 text-blue-700 border-blue-300 border'
                  : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
              }`}
              onClick={() => setSelectedType(type.value)}
            >
              <FontAwesomeIcon icon={type.icon} className="mr-2" />
              {type.label}
            </button>
          ))}

          <button className="ml-2 flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-gray-700 bg-white border border-gray-300 hover:bg-gray-50">
            <FontAwesomeIcon icon={faDownload} className="mr-2" />
            导出
          </button>
        </div>
      </div>

      {/* 数据表格 */}
      <DataTable
        columns={columns}
        data={filteredData}
        title="健康数据列表"
        description={`共 ${filteredData.length} 条记录`}
        onView={handleView}
        onEdit={handleEdit}
        onDelete={handleDelete}
        pagination={true}
        pageSize={8}
      />
    </AdminLayout>
  );
} 